package com.community.common.util;

import com.google.common.cache.*;
import lombok.Builder;
import lombok.Data;

import java.util.concurrent.TimeUnit;

public class CacheUtil {

    //LoadingCache在缓存项不存在时可以自动加载缓存
   public static LoadingCache<String,Object> cache = CacheBuilder.newBuilder()
            //设置并发级别为8，并发级别是指可以同时写缓存的线程数
            .concurrencyLevel(8)
            //设置写缓存后10分钟过期
            .expireAfterWrite(10, TimeUnit.MINUTES)
            //设置缓存容器的初始容量为10
            .initialCapacity(10)
            //设置缓存最大容量为100，超过100之后就会按照LRU最近虽少使用算法来移除缓存项
            .maximumSize(100)
            //设置缓存的移除通知
            .removalListener(new RemovalListener<String, Object>() {
                @Override
                public void onRemoval(
                        RemovalNotification<String, Object> notification) {
                    System.out.println(notification.getKey() + " was removed, cause is " + notification.getCause());
                }
            })
            //设置要统计缓存的命中率
            .recordStats()
            .build(new CacheLoader<String, Object>(){
                @Override
                public Object load(String key) throws Exception {
                    return null;
                }
            });

    public static void main(String[] args) {
        OpenDoorElement openDoorElement = OpenDoorElement.builder()
                .sn("qwe")
                .startTimeMillis(System.currentTimeMillis())
                .status(OpenDoorEnum.WAITING.name())
                .build();
        cache.put("sn",openDoorElement);
    }

    @Data
    @Builder
    public static class OpenDoorElement {

        private String sn;

        private String status;

        private String msg;

        private long startTimeMillis;

    }

    public enum OpenDoorEnum{
        WAITING,
        SUCCESS,
        FAIL;
    }

}
